﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RXY_Mall.Core.Tool
{
    public class CompareHelper
    {
        /// <summary>
        /// 比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0 
        /// </summary>
        /// <param name="version1"></param>
        /// <param name="version2"></param>
        /// <returns></returns>
        public static int CompareVersion(String version1, String version2)
        {
            int diff = 0;
            try
            {
                if (version1 == null || version2 == null)
                {
                    throw new Exception("compareVersion error:illegal params.");
                }
                String[]
                versionArray1 = version1.Split('.');//注意此处为正则匹配，不能用"."；  
                String[]
                versionArray2 = version2.Split('.');
                int idx = 0;
                int minLength = Math.Min(versionArray1.Length, versionArray2.Length);//取最小长度值  

                while (idx < minLength
                        && (diff = versionArray1[idx].Length - versionArray2[idx].Length) == 0//先比较长度  
                        && (diff = versionArray1[idx].CompareTo(versionArray2[idx])) == 0)
                {
                    //再比较字符  
                    ++idx;
                }
                //如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；  
                diff = (diff != 0) ? diff : versionArray1.Length - versionArray2.Length;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            return diff;
        }
    }
}
